package servlet;

import java.io.IOException;
import java.util.LinkedList;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import domain.Movie;
import domain.User;
import ex.AuthenticationFailedException;
import ex.DatabaseException;

import service.MovieService;
import service.UserService;
import sun.rmi.server.UnicastServerRef;

public class Home extends HttpServlet {

	UserService userService=new UserService();
	MovieService movieService=new MovieService();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		LinkedList<Movie> topMovies = new LinkedList<Movie>();
		LinkedList<Movie> latestMovies = new LinkedList<Movie>();
		try {
			topMovies = movieService.getTopMovies();
			latestMovies = movieService.getLatestMovies();
			request.setAttribute("topMovies", topMovies);
			request.setAttribute("latestMovies", latestMovies);
		} catch (DatabaseException e) {
			request.setAttribute("loginError", e.getMessage());
		}
		String action=request.getParameter("action");
		if(action!=null && action.equals("logout"))
		{
			HttpSession session = request.getSession();
			if(session!=null)
				session.invalidate();			
		}
		RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/home.jsp");
		if (dispatcher != null) dispatcher.forward(request, response);
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		try{
			String email=request.getParameter("email");
			String password=request.getParameter("password");
			
			User user=userService.authenticateUser(email, password);
			
			if(user!=null){
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
			}
			else{
				request.setAttribute("loginError", "Invalid username or password!");
			}		
		}
		catch (AuthenticationFailedException e) {
			request.setAttribute("loginError", e.getMessage());
		}
		catch (DatabaseException e) {
			request.setAttribute("loginError", e.getMessage());
		}
		catch (Exception e) {
			request.setAttribute("loginError", "A general error occured");
		}
		finally{
			RequestDispatcher dispatcher = request.getRequestDispatcher("jsp/user/home.jsp");
			if (dispatcher != null) dispatcher.forward(request, response);
		}
	}

}
